﻿using FreeSql;
using Microsoft.Extensions.DependencyInjection;

namespace Msung.Core.Freesql
{
    public static class MultiDBSetup
    {

        public static void AddMultiDB(this IServiceCollection services)
        {


            //Func<IServiceProvider, IFreeSql<MySqlFlag>> fsql1 = r =>
            //{
            //    var fsql1 = new FreeSqlBuilder().UseConnectionString(DataType.Oracle, "str1")
            //        .Build<MySqlFlag>();
            //    return fsql1;
            //};
            //Func<IServiceProvider, IFreeSql<SqlServerFlag>> fsql2 = r =>
            //{
            //    var fsql2 = new FreeSqlBuilder().UseConnectionString(DataType.Oracle, "str1")
            //        .Build<SqlServerFlag>();
            //    return fsql2;
            //};

            //services.AddSingleton<IFreeSql<MySqlFlag>>(fsql1);
            //services.AddSingleton<IFreeSql<SqlServerFlag>>(fsql2);


            //var fsql = new MultiFreeSql<string>();
            //List<MultiDb> dbsList = AppSetting.MultiDbs;
            //if (dbsList.Any())
            //{
            //    foreach (var dbObj in dbsList)
            //    {
            //        var freesql = new FreeSqlBuilder().UseConnectionString(dbObj.DbType, dbObj.ConnectionString).Build();
            //        //fsql.Aop.CurdAfter += (s, e) =>
            //        // Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: " +
            //        // $"{e.EntityType.FullName} " +
            //        // $"{e.ElapsedMilliseconds}ms, " +
            //        // $"{e.Sql}");
            //        fsql.Register(dbObj.Name, () => freesql);
            //    }
            //}
            var fsql = new FreeSqlCloud<string>(); //提示：泛型可以传入 string
            List<MultiDb> dbsList = AppSetting.MultiDbs;
            if (dbsList.Any())
            {
                foreach (var dbObj in dbsList)
                {
                    fsql.Register(dbObj.Name, () =>
                    new FreeSqlBuilder()
                    .UseNoneCommandParameter(true)
                    .UseConnectionString(dbObj.DbType, dbObj.ConnectionString)
                    .Build());
                    fsql.Aop.CurdAfter += (s, e) =>
                    {
                        Console.WriteLine($"{Thread.CurrentThread.ManagedThreadId}: " + $"{e.EntityType.FullName} " + $"{e.ElapsedMilliseconds}ms, " + $"{e.Sql}");
                    };
                    fsql.Aop.CurdBefore += (s, e) =>
                    {

                    };
                }
            }
            fsql.DistributeTrace = log => Console.WriteLine(log.Split('\n')[0].Trim());
            
            services.AddSingleton<IFreeSql>(fsql);
            services.AddSingleton(fsql);
        }
    }
}
